package servlets;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ActionServlet.
 */
public class ActionServlet extends HttpServlet {
    /** Serial version UID. */
    private static final long serialVersionUID = 1L;

    /**
     * Initializes the servlet.
     *
     * @param config  configuration data of the servlet
     * @throws ServletException  if there is any problem
     */
    @Override
    public void init(final ServletConfig config) throws ServletException {
        super.init(config);
    }

    /**
     * Return the main view.
     *
     * @param request  HTTP request
     * @param response  HTTP response
     * @throws ServletException  if there is any problem
     * @throws IOException  if there is any problem
     * @see HttpServlet#doGet(HttpServletRequest request,
     *                           HttpServletResponse response)
     */
    @Override
    protected void doGet(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        getServletContext().getRequestDispatcher(
                "/jsp/readerMainView.jsp").forward(request, response);
    }

    /**
     * Read the action the user wants to perform and return the corresponding
     * view.
     *
     * @param request  HTTP request
     * @param response  HTTP response
     * @throws ServletException  if there is any problem
     * @throws IOException  if there is any problem
     * @see HttpServlet#doPost(HttpServletRequest request,
     *                            HttpServletResponse response)
     */
    @Override
    protected void doPost(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action.startsWith("Subscribe")) {
            //TODO: have the names of the available newspapers
            //in the right place
            //now they are in the app context
            getServletContext().getRequestDispatcher(
                    "/jsp/selectNewspapers.jsp").forward(request, response);
        } else if (action.startsWith("Read")) {
            getServletContext().getRequestDispatcher(
                    "/read").forward(request, response);
        } else if (action.startsWith("Manage")) {
            getServletContext().getRequestDispatcher(
                    "/jsp/manageSubscriptions.jsp").forward(request, response);
        } else if (action.startsWith("Publish")) {
            getServletContext().getRequestDispatcher(
                    "/publish").forward(request, response);
        } else {
            throw new ServletException("Action not recognized");
        }
    }

}
